<?php

namespace App\Supports\Auth\Alipay;

use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Rainsens\Dinglog\Facades\Dinglog;

class AlipayBinder extends AlipayAuthUser
{
	protected $authData;

	public function httpValidate()
	{
		$code = request('code');

		try {
			$accessToken = $this->getAccessTokenFromCode($code);
			$this->authData = $this->getUserFromToken($accessToken);
			Dinglog::text(json_encode($this->authData));
			if ($this->isAlipayBound()) {
                fail('支付宝已被其它账号绑定');
			}
		} catch (Exception $e) {
            $code = $e->getCode();
            $message = $e->getMessage();
            Dinglog::text("支付宝绑定失败：{$code}:{$message}");
            fail('支付宝绑定失败');
		}
	}

	public function isAlipayBound(): bool
	{
		$data = $this->authData;
		$alipayUserId = $data['user_id'] ?? '';

		$boundUser = null;
		if ($alipayUserId) {
			$boundUser = User::where('alipay_user_id', $alipayUserId)->first();
		}

		return (bool)$boundUser;
	}

	protected function bindAccount(User $user)
	{
		$this->httpValidate();

		$data = $this->authData;

		$user->update([
			'alipay_user_id' => $data['user_id'],
			'alipay_nickname' => isset($data['nick_name']) ? $data['nick_name'] : null,
			'alipay_avatar' => isset($data['avatar']) ? $data['avatar'] : null,
			'alipay_province' => isset($data['province']) ? $data['province'] : null,
			'alipay_city' => isset($data['city']) ? $data['city'] : null,
		]);

		return $user;
	}

	public function bind(User $user)
	{
		return $this->bindAccount($user);
	}

	protected function dismissAccount(User $user)
	{
		$user->update([
			'alipay_user_id' => null,
			'alipay_nickname' => null,
			'alipay_avatar' => null,
			'alipay_province' => null,
			'alipay_city' => null,
		]);
	}

	public function dismiss(User $user)
	{
		$this->dismissAccount($user);
	}
}
